<?php

namespace app\api\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Green\Green;
use app\api\model\MsgLog;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use app\RedisAdmin;
use app\RedisApi;
use fast\Random;
use OSS\OssClient;
use think\Config;
use think\Db;
use think\Exception;
use think\Hook;
use think\Log;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init','upload'];
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng     经度
     * @param string $lat     纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

//    /**
//     * 上传文件
//     * @ApiMethod (POST)
//     * @param File $file 文件流
//     */
//    public function upload()
//    {
//        Config::set('default_return_type', 'json');
//        //必须设定cdnurl为空,否则cdnurl函数计算错误
//        Config::set('upload.cdnurl', '');
//        $chunkid = $this->request->post("chunkid");
//        if ($chunkid) {
//            if (!Config::get('upload.chunking')) {
//                $this->error(__('Chunk file disabled'));
//            }
//            $action = $this->request->post("action");
//            $chunkindex = $this->request->post("chunkindex/d");
//            $chunkcount = $this->request->post("chunkcount/d");
//            $filename = $this->request->post("filename");
//            $method = $this->request->method(true);
//            if ($action == 'merge') {
//                $attachment = null;
//                //合并分片文件
//                try {
//                    $upload = new Upload();
//                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
//                } catch (UploadException $e) {
//                    $this->error($e->getMessage());
//                }
//                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
//            } elseif ($method == 'clean') {
//                //删除冗余的分片文件
//                try {
//                    $upload = new Upload();
//                    $upload->clean($chunkid);
//                } catch (UploadException $e) {
//                    $this->error($e->getMessage());
//                }
//                $this->success();
//            } else {
//                //上传分片文件
//                //默认普通上传文件
//                $file = $this->request->file('file');
//                try {
//                    $upload = new Upload($file);
//                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
//                } catch (UploadException $e) {
//                    $this->error($e->getMessage());
//                }
//                $this->success();
//            }
//        } else {
//            $attachment = null;
//            //默认普通上传文件
//            $file = $this->request->file('file');
//            try {
//                $upload = new Upload($file);
//                $attachment = $upload->upload();
//            } catch (UploadException $e) {
//                $this->error($e->getMessage());
//            }
//
//            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
//        }
//
//    }

    /**
     * @param $params
     * ['photo']        // 图片地址
     * ['quality']      // 图片压缩后的质量 值范围: 1 - 75 默认值 50
     * ['like_width']   // 偏好宽度, 如果图片宽度大于该宽度值 会自动压缩为该宽度的数字大小 默认为 900PX
     * ['cover']        // 是否覆盖原图 0为不覆盖 1为覆盖
     * @return false|string
     */
    public function upload()
    {
        $file = request()->file('file');
        $fileNow = request()->file('file')->getInfo();
        $type = $this->request->post('type',1); //请求信息

        $name = $fileNow['name'];
        $info = $file->move('./uploads');
        $file_name = $info->getFilename();
        $arr = pathinfo($file_name);
        $ext = $arr['extension'];
        if($type==1){
            if(!in_array($ext,['jpg','gif','png','jpeg'])){
                $this->error(1);
            }
        }else{
            if(!in_array($ext,['doc','xls','ppt','pdf','docx','xlsx','pptx'])){
                $this->error(2);
            }
        }

        $data_log = [
            'file'=>$file,
            'fileNow'=>$fileNow,
            'file_name'=>$file_name,
            '$type'=>$type,
        ];
        file_put_contents("up_t.txt", json_encode($data_log). PHP_EOL, FILE_APPEND);
        //    var_dump($info);
        $date = date('Ymd');
        if ($info) {

            $data['code'] = 0;
            $data['img'] = 'uploads/' . $date . '/' . $info->getFilename();

        }

        //     var_dump($ww);
        //  var_dump($fileNow);
        $name = 'uploads/' . $date . '/' . $info->getFilename();
        $savePath = str_replace("\\","/",$name);

        // $object = $category.'/'.$savePath;//想要保存文件的名称

        // $sy_photo = $this->addWatermark($new_photo_name);
        //  $savePath = str_replace("\\","/",$sy_photo);
        $file = $savePath;//文件路径，必须是本地的
        //  $file = $savePath;//文件路径，必须是本地的
        $ossClient = new OssClient('LTAI5tHDQ3jN4HQhtsPGPhvo', 'TMfPpCWNrORoyV7K8V9Xv9ZPJLRTeo', 'oss-cn-beijing.aliyuncs.com');  //
        $result = $ossClient->uploadFile('txw-frontpage', $name, $savePath);
//        } catch (OssException $e) {
//            var_dump($e);exit;
//            $this->error('上传失败');
//        }
        $ossurl = $result["info"]["url"];
        unlink($data['img']);

        unset($info);
        //   unlink($name);
        //nlink($sy_photo);
        //  var_dump($ossurl);
        $ossurl = str_replace('http','https',$ossurl);
        $ossurl_arr = explode('aliyuncs.com',$ossurl);

        $this->success(__('Uploaded successful'), ['url' => $ossurl_arr[1], 'fullurl' => $ossurl]);
//        $this->success(__('Upload successful'), [
//            'code'=>0,
//            'img' => $new_name
//        ],200);
    }

    /**
     * @param $params
     * ['photo']        // 图片地址
     * ['quality']      // 图片压缩后的质量 值范围: 1 - 75 默认值 50
     * ['like_width']   // 偏好宽度, 如果图片宽度大于该宽度值 会自动压缩为该宽度的数字大小 默认为 900PX
     * ['cover']        // 是否覆盖原图 0为不覆盖 1为覆盖
     * @return false|string
     */
    public function upload1()
    {
        $type = $this->request->request('type', 2);
        $file = request()->file('file');
        $fileNow = request()->file('file')->getInfo();
        $today_time = date('Y-m-d');
        $name = $fileNow['name'];
        //   var_dump($fileNow);
        $info = $file->move('./uploads');
        //    var_dump($info);
        $date = date('Ymd');

        //     var_dump($ww);
        //  var_dump($fileNow);
        $new_name = $name = 'uploads/' . $date . '/' . $info->getFilename();

        $this->success(__('Uploaded successful'), ['url' => $new_name, 'fullurl' => cdnurl($new_name, true)]);
//        $this->success(__('Upload successful'), [
//            'code'=>0,
//            'img' => $new_name
//        ],200);
    }
    public function  getAppletToken($type = 1){
        try{
            $appId = Config::get('site.appId');
            $appSecret = Config::get('site.appSecret');
            $access_token_redis = RedisApi::getInstance()->hGet('applet_access_token',['expires_in','access_token']);  //判断access——tokens是否过期
            $today_time = date('Y-m-d');
            $data = [
                'info'=>$access_token_redis,
                'time'=>date('Y-m-d H:i:s'),
            ];
            //    file_put_contents("getAppletToke_".$today_time.".txt", json_encode($data). PHP_EOL, FILE_APPEND);
            if($access_token_redis['access_token']){
                $access_token_info = [
                    'status_time'=>$access_token_redis['expires_in'],
                    'access_token'=>$access_token_redis['access_token'],
                ];
                $access_token_info = json_encode($access_token_info);
            }else{
                $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
                $get_access_token_result = httpCurl($access_token_url,'get');
                $today_time = date('Y-m-d');
                $data_log = [
                    'sql'=>$get_access_token_result,
                    'appId'=>$appId,
                    'appSecret'=>$appSecret,
                    'time'=>date('Y-m-d H:i:s'),
                ];
                //    file_put_contents("get_applet_access_token_".$today_time.".txt", json_encode($data_log). PHP_EOL, FILE_APPEND);
                $access_token_result = $get_access_token_result;
                if(isset($access_token_result['errcode'])){
                    $this->error($access_token_result['errmsg']);
                }
                $access_token_info = [
                    'status_time'=>$access_token_result['expires_in'],
                    'access_token'=>$access_token_result['access_token'],
                ];
                $access_token_info = json_encode($access_token_info);
                RedisApi::getInstance()->hSet('applet_access_token',$access_token_result,$access_token_result['expires_in']);
            }
            if($type==1){
                echo $access_token_info;
            }else{
                return $access_token_info;
            }

        }catch (Exception $e){
            Log::error("获取小程序token错误信息：" .PHP_EOL
                . "time:" . date('Y-m-d H:i:s') . PHP_EOL
                . "error:" . $e->getMessage() . PHP_EOL
                . "file:" . $e->getFile() . PHP_EOL
                . "line:" . $e->getLine() . PHP_EOL
            );
        }

    }


    /**
     * xml转数组
     */
    public  function xmlToArray($string=''){
        $objectxml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
        $xmljson= json_encode($objectxml);
        $xmlarray=json_decode($xmljson,true);
        return $xmlarray;
    }

    /**
     * 保存消息记录
     * @param $json_string
     * @return bool
     */
    public function saveMsgLog($json_string,$type=1,$json_data){
        $data = [
            'json'=>$json_string,
            'created_at'=>date('Y-m-d H:i:s'),
            'type'=>$type,
            'createtime'=>time()
        ];
        if($type == 1){
            $data['FromUser'] = $json_data['FromUserName'];
        }else{
            $data['touser'] = $json_data['touser'];
        }
//        $model = new MsgLog();
//        if ($model->insert($data)){
//            return true;
//        }
        return false;
    }

    /**
     * 向微信客服平台发送消息给用户
     * @param $data
     * @param $access_token
     */
    public static function send($data,$access_token){
        try{
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
            $data_new = urldecode(json_encode($data,JSON_UNESCAPED_UNICODE));
            //(new Common)->saveMsgLog($data_new,2,$data);
            (new Common)->curl_post($url,$data_new);
        }catch (Exception $e){
            Log::error("微信客服send错误信息：" .PHP_EOL
                . "time:" . date('Y-m-d H:i:s') . PHP_EOL
                . "error:" . $e->getMessage() . PHP_EOL
                . "file:" . $e->getFile() . PHP_EOL
                . "line:" . $e->getLine() . PHP_EOL
            );
        }

    }

    /**
     * post请求
     */
    public  function curl_post($url,$post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $ch_ex = curl_exec($ch);
        curl_close($ch);
        if(!$ch_ex){
            return false;
        }else{
            $res = json_decode($ch_ex,1);
            if($res['errcode'] == 40001){
                RedisApi::getInstance()->delete('applet_access_token');
            }
            $data = [
                'send_data'=>$res,
                'time'=>date('Y-m-d H:i:s'),
            ];
            file_put_contents("curl_post_kf.txt", json_encode($data). PHP_EOL, FILE_APPEND);
            return $res;
        }
    }

    public   function  checkInfo($ossurl,$type){

        try{
            if($type == 2){
                AlibabaCloud::accessKeyClient($this->accesskeyid, $this->accesskeySecret)
                    ->regionId('cn-shanghai')
                    ->asDefaultClient();
                $task1 = array('dataId' => get_rand_num(10),
                    'url' => $ossurl
                );
                /**
                 * 文本垃圾检测：antispam。
                 **/
                $result = Green::v20180509()->imageSyncScan()
                    ->body(json_encode(array('tasks' => array($task1), 'scenes' => array("porn","terrorism","live"))))
                    ->request();
                $info = $result->toArray();
                $text ='';
                $text_type =1;
            }else{
                AlibabaCloud::accessKeyClient($this->accesskeyid, $this->accesskeySecret)
                    ->regionId('cn-shanghai')
                    ->asDefaultClient();
                $task1 = array('dataId' => get_rand_num(10),
                    'url' => $ossurl
                );
                /**
                 * 文本垃圾检测：antispam。
                 **/
                $result = Green::v20180509()->videoSyncScan()
                    ->body(json_encode(array('tasks' => array($task1), 'scenes' => array("porn","terrorism","live"))))
                    ->request();
                $info = $result->toArray();
                $text ='';
                $text_type =1;

            }
            Log::notice("上铺图片视频数据垃圾信息：" .PHP_EOL
                . "time:" . date('Y-m-d H:i:s') . PHP_EOL
                . "text:" . $text . PHP_EOL
                . "type:" . $type . PHP_EOL
                . "data:" . json_encode($info) . PHP_EOL
            );
            foreach ($info['data'][0]['results'] as $w=>$v){
                if($v['suggestion'] != 'pass'){
                    $text = $v['label'].'-'.$v['scene'];
                    $text_type =2;
                }

            }

            if($text_type == 2){
                $this->error('info error');
            }
//            if($info['data'][0]['results'][0]['suggestion'] != 'pass'){
//
//
//                // $this->error($text);
//            }
            //   print_r($result->toArray());
        } catch (ClientException $exception) {
            Log::error("上铺图片记录校验信息报错1：" .PHP_EOL
                . "time:" . date('Y-m-d H:i:s') . PHP_EOL
                . "getMessage:" . $exception->getMessage() . PHP_EOL
                . "type:" . $type . PHP_EOL
            );
        } catch (ServerException $exception) {
            Log::error("上铺图片记录校验信息报错：" .PHP_EOL
                . "time:" . date('Y-m-d H:i:s') . PHP_EOL
                . "error:" . $exception->getMessage() . PHP_EOL
                . "errorcode:" . $exception->getErrorCode() . PHP_EOL
                . "type:" . $type . PHP_EOL
                . "getRequestId:" . $exception->getRequestId() . PHP_EOL
                . "getErrorMessage:" . $exception->getErrorMessage() . PHP_EOL
            );
        }
    }
    /**
     * 按照指定的尺寸压缩图片
     * @param $source_path  原图路径
     * @param $target_path  保存路径
     * @param $imgWidth     目标宽度
     * @param $imgHeight    目标高度
     * @return bool|string
     */
    public function resize_image($source_path,$target_path,$imgWidth,$imgHeight)
    {
        $source_info = getimagesize($source_path);
        // var_dump($source_info);
        $source_mime = $source_info['mime'];
        $ext = pathinfo($source_path,PATHINFO_EXTENSION);
        $new_photo_name = md5(time() . mt_rand(1000, 9999)) . '.' . $ext;
        $imgWidth = $source_info['0'];
        $imgHeight = $source_info[1];
        $date = date('Ymd');
        $new_photo_name = 'tempdir/' . $date . '/' . $new_photo_name;
        switch ($source_mime)
        {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;

            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;

            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;

            default:
                return false;
                break;
        }
        $target_image     = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图
        imagecopyresampled($target_image, $source_image, 0, 0, 0, 0, $imgWidth, $imgHeight, $source_info[0], $source_info[1]);
        //保存图片到本地
        $dir = '/uploads/' . $date . '/';
//        if (!is_dir($dir)) {
//            mkdir($dir, 0777);
//        }
//
        $fileName = $dir.date("YmdHis").uniqid().'.jpg';
        if(!imagejpeg($target_image,'./'.$fileName)){
            $fileName = '';
        }
        imagedestroy($target_image);
        return $fileName;
    }

    /**
     * @title 设置小程序推送
     */
    public function  send_notice1($student_id,$status){
        try{
            $access_token_info = $this->getAppletToken(2);
            //   $access_token_info = $this->getAppletToken(2);
            $access_token_info = json_decode($access_token_info,true);
            $access_token = $access_token_info['access_token'];
            $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
            foreach ($student_id as $w=>$v){
                $parents_id = Db::name('student')->where(['id'=>$v])->value('parents_id');
                $student_name = Db::name('student')->where(['id'=>$v])->value('student_name');
                $parent_id_arr = Db::name('parent_bind')->where(['student_id'=>$v])->column('parent_id');
                if(count($parent_id_arr)>0){
                    foreach ($parent_id_arr as $ww=>$vv){
                        $openid = Db::name('user')->where(['id'=>$vv])->value('openid');
                        if($openid != null){
                            $data = [
                                'touser'=>$openid,
                                'template_id'=>'s5Js9rk54U4eoWj9rFtfDOY4qevtUzn6t4tX6B9YKvI',
                                //   'template_id'=>'ZC9zSiCNI1Gfi0BfOn2fSazSdtrYkjdaonoL_tgY8r0',
                                'page'=>'pages/index/index',
                                'miniprogram_state'=>'formal',
                                'lang'=>'zh_CN',
                            ];
//                       $data['data'] = [
//                           'thing1'=>['value'=>'您有未读消息，请查收'],
//                           'thing2'=>['value'=>'您有未读消息，请查收'],
//                           'date3'=>['value'=>date('Y-m-d H:i:s',$v['createtime'])],
//                           'thing4'=>['value'=>'您有未读消息，请查收'],
//                       ];
                            $content = '';
                            switch ($status){
                                case 1:
                                    $content = '已接到您的孩子';
                                    break;
                                case 2:
                                    $content = '您的孩子已下课';
                                    break;
                            }
                            $data['data'] = [
                                //  'first'=>$content,
                                'name1'=>['value'=>$student_name],
                                //   'thing3'=>['value'=>$content],
                                'time2'=>['value'=>date('Y-m-d H:i:s',time())],
                                'thing5'=>['value'=>$content],
                            ];
                            $post_data = json_encode($data);
                            $result = $this->httpCurl($url,'post','json',$post_data);
                            //       var_dump($result);
                            //  $result = json_decode($result,true);
                            if($result['errcode'] != 0){
//                        if($result['errcode'] == 40001){
//
//                        }
                                $today_time = date('Y-m-d');
                                $datas = [
                                    'info'=>$result,
                                    'user_id'=>$v,
                                    'parent_id'=>$vv,
                                    'open_id_arr'=>$openid,
                                    'time'=>date('Y-m-d H:i:s'),
                                ];
                                //  Log::notice('小程序未读消息推送错误信息'.json_encode($datas));
                                file_put_contents("send_info_result_".$today_time.".txt", json_encode($datas). PHP_EOL, FILE_APPEND);
                                continue;
                            }
                            $today_time = date('Y-m-d');
                            $datas = [
                                'info'=>$result,
                                'user_id'=>$v,
                                'parent_id'=>$vv,
                                'open_id_arr'=>$openid,
                                'time'=>date('Y-m-d H:i:s'),
                            ];
                            Log::notice('小程序未读消息推送ok'.json_encode($datas));
                        }else{
                            $datas = [
                                'parents_id'=>$parents_id,
                                'user_id'=>$v,
                                'parent_id'=>$vv,
                                'open_id_arr'=>$openid,
                                'time'=>date('Y-m-d H:i:s'),
                            ];
                            Log::notice('小程序推送失败ok'.json_encode($datas));
                            continue;
                        }
                    }
                }


            }
            return json_encode(['code'=>200]);
        }catch (Exception $e){
            Log::error("小程序推送未读消息报错：" .PHP_EOL
                . "time:" . date('Y-m-d H:i:s') . PHP_EOL
                . "error:" . $e->getMessage() . PHP_EOL
                . "file:" . $e->getFile() . PHP_EOL
                . "line:" . $e->getLine() . PHP_EOL
            );
            //throw new Exception($e->getMessage());
        }

    }
    public function  send_notice($student_id,$status){
        $appid = "wx9ec960dadf971791";
        $secret = "5d31e7dd4bc43f5701064dc2a936add7";
        $access_token_redis = RedisApi::getInstance()->hGet('applet_new_access_token',['expires_in','access_token']);  //判断access——tokens是否过期
        $today_time = date('Y-m-d');
        $data = [
            'info'=>$access_token_redis,
            'time'=>date('Y-m-d H:i:s'),
        ];
        //    file_put_contents("getAppletToke_".$today_time.".txt", json_encode($data). PHP_EOL, FILE_APPEND);
        if($access_token_redis['access_token']){
            $access_token_info = [
                'status_time'=>$access_token_redis['expires_in'],
                'access_token'=>$access_token_redis['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
        }else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $token = $this->getJson($url);
            $get_access_token_result = json_decode($token, true);
//            $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
//            $get_access_token_result = httpCurl($access_token_url,'get');
            $today_time = date('Y-m-d');
            $data_log = [
                'sql'=>$get_access_token_result,
//                'appId'=>$appId,
//                'appSecret'=>$appSecret,
                'time'=>date('Y-m-d H:i:s'),
            ];
            //    file_put_contents("get_applet_access_token_".$today_time.".txt", json_encode($data_log). PHP_EOL, FILE_APPEND);
            $access_token_result = $get_access_token_result;
            if(isset($access_token_result['errcode'])){
                $this->error($access_token_result['errmsg']);
            }
            $access_token_info = [
                'status_time'=>$access_token_result['expires_in'],
                'access_token'=>$access_token_result['access_token'],
            ];
            $access_token_info = json_encode($access_token_info);
            RedisApi::getInstance()->hSet('applet_new_access_token',$access_token_result,$access_token_result['expires_in']);
        }
        $access_token_info = json_decode($access_token_info,true);
        //   var_dump($access_token_info);
        $uri ='https://api.weixin.qq.com/cgi-bin/message/template/send';
        $access_token = $access_token_info["access_token"];
        $uri = $uri.'?access_token='.$access_token;
        $content = '';
        $new_content = '';
        $template_id = '';
        switch ($status){
            case 1:
                $content = '已接到您的孩子';
                $new_content = '签到';
                $template_id = 'RMsmKaedAfq2EINdeh_pJnS-dnFiNGx2LJWxYE2NKZI';
                break;
            case 2:
                $content = '您的孩子已下课';
                $template_id = '5Zsazr5xxHWCeTm3Im6bqY9zYCs3xjrAM-O7AtHve_o';
                $new_content = '签退';
                break;
        }
        foreach ($student_id as $w=>$v){
            $parents_id = Db::name('student')->where(['id'=>$v])->value('parents_id');
            $student_name = Db::name('student')->where(['id'=>$v])->value('student_name');
            $parent_id_arr = Db::name('parent_bind')->where(['student_id'=>$v])->column('parent_id');
            $datas = [
                'user_id'=>$v,
                'parent_id'=>$parent_id_arr,
                'time'=>date('Y-m-d H:i:s'),
            ];
            //  Log::notice('小程序未读消息推送错误信息'.json_encode($datas));
            file_put_contents("send_info_result1_".$today_time.".txt", json_encode($datas). PHP_EOL, FILE_APPEND);
            if(count($parent_id_arr)>0){
                foreach ($parent_id_arr as $ww=>$vv){

                    $openid = Db::name('gzh_openid')->where(['user_id'=>$vv])->value('openid');
                    $datas = [
                        'user_id'=>$v,
                        'parent_id'=>$vv,
                        'open_id_arr'=>$openid,
                        'time'=>date('Y-m-d H:i:s'),
                    ];
                    //  Log::notice('小程序未读消息推送错误信息'.json_encode($datas));
                    file_put_contents("send_info_result_".$today_time.".txt", json_encode($datas). PHP_EOL, FILE_APPEND);
                   // $openid = Db::name('user')->where(['id'=>$vv])->value('openid');
                    if($openid != null){
                        $data=  array('touser'=>$openid,   //发给谁
                            'template_id'=>$template_id,   //模板id
                            // 'url'=>'pages/index/index',     //这个是你发送了模板消息之后，当用户点击时跳转的连接
                            'topcolor'=>"#FF0000",   //颜色
                            'miniprogram'=>[ "appid"=>"wx8b97b45b7bddef4c",
                                "pagepath"=>"pages/index/index"],
                            'data'=>array(
                                'first'=>array(
                                    'value'=>'您的孩子有一条新到记录',
                                    'color'=>'#173177'
                                ),
                                'keyword1'=>array(
                                    'value'=>$student_name,
                                    'color'=>'#173177'
                                ),
                                'keyword2'=>array(
                                    'value'=>date('Y-m-d H:i:s'),
                                    'color'=>'#173177'
                                ),
                                'keyword3'=>array(
                                    'value'=>$new_content,
                                    'color'=>'#173177'
                                ),
                                'keyword4'=>array(
                                    'value'=>$content,
                                    'color'=>'#173177'
                                ),
//                                'remark'=>array(
//                                    'value'=>'已接到您的孩子',
//                                    'color'=>'#173177'
//                                )
                            )
                        );
                        $res_data = $this->getJson($uri,$data);
                        $res_data = json_decode($res_data, true);
                        if (isset($res_data['errcode']) && $res_data['errcode'] != 0) {
                            $today_time = date('Y-m-d');
                            $datas = [
                                'info'=>$res_data,
                                'user_id'=>$v,
                                'parent_id'=>$vv,
                                'open_id_arr'=>$openid,
                                'time'=>date('Y-m-d H:i:s'),
                            ];
                            //  Log::notice('小程序未读消息推送错误信息'.json_encode($datas));
                            file_put_contents("send_info_no-result_".$today_time.".txt", json_encode($datas). PHP_EOL, FILE_APPEND);
                            continue;
                        }
                        $today_time = date('Y-m-d');
                        $datas = [
                            'info'=>$res_data,
                            'user_id'=>$v,
                            'parent_id'=>$vv,
                            'open_id_arr'=>$openid,
                            'time'=>date('Y-m-d H:i:s'),
                        ];
                        Log::notice('小程序未读消息推送ok'.json_encode($datas));
                    }else{
                        $datas = [
                            'parents_id'=>$parents_id,
                            'user_id'=>$v,
                            'parent_id'=>$vv,
                            'open_id_arr'=>$openid,
                            'time'=>date('Y-m-d H:i:s'),
                        ];
                        Log::notice('小程序推送失败ok'.json_encode($datas));
                        continue;
                    }
                }
            }


        }
        return json_encode(['code'=>200]);
        $this->success('更新成功');
    }


    /**
     * @title curl函数
     * @param        $url
     * @param string $type
     * @param string $res
     * @param string $arr
     * @return mixed
     */
    public function httpCurl($url, $type = 'get', $res = 'json', $arr = '') {
        try{
            //1.初始化curl
            $ch = curl_init();
            //2.设置curl的参数
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // curl_setopt($ch,CURLOPT_PROXY,'58.246.220.31:443');
            if ($type == 'post') {
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
            }
            //3.采集
            $output = curl_exec($ch);
            //4.关闭
            curl_close($ch);
            if ($res == 'json') {
                return json_decode($output, true);
            }
            return $output;
        }catch (Exception $e){
            Log::error("httpCurl错误信息：" .PHP_EOL
                . "time:" . date('Y-m-d H:i:s') . PHP_EOL
                . "error:" . $e->getMessage() . PHP_EOL
                . "file:" . $e->getFile() . PHP_EOL
                . "line:" . $e->getLine() . PHP_EOL
            );
        }

    }
//    /**
//     * 按照指定的尺寸压缩图片
//     * @param $source_path  原图路径
//     * @param $target_path  保存路径
//     * @param $imgWidth     目标宽度
//     * @param $imgHeight    目标高度
//     * @return bool|string
//     */
//    public function resize_image($source_path,$target_path,$imgWidth,$imgHeight)
//    {
//        $source_info = getimagesize($source_path);
//        // var_dump($source_info);
//        $source_mime = $source_info['mime'];
//        $ext = pathinfo($source_path,PATHINFO_EXTENSION);
//        $new_photo_name = md5(time() . mt_rand(1000, 9999)) . '.' . $ext;
//        $imgWidth = $source_info['0'];
//        $imgHeight = $source_info[1];
//        $date = date('Ymd');
//        $new_photo_name = 'tempdir/' . $date . '/' . $new_photo_name;
//        switch ($source_mime)
//        {
//            case 'image/gif':
//                $source_image = imagecreatefromgif($source_path);
//                break;
//
//            case 'image/jpeg':
//                $source_image = imagecreatefromjpeg($source_path);
//                break;
//
//            case 'image/png':
//                $source_image = imagecreatefrompng($source_path);
//                break;
//
//            default:
//                return false;
//                break;
//        }
//        $target_image     = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图
//        imagecopyresampled($target_image, $source_image, 0, 0, 0, 0, $imgWidth, $imgHeight, $source_info[0], $source_info[1]);
//        //保存图片到本地
//        $dir = 'tempdir/' . $date . '/';
////        if (!is_dir($dir)) {
////            mkdir($dir, 0777);
////        }
////
//        $fileName = $dir.date("YmdHis").uniqid().'.jpg';
//        if(!imagejpeg($target_image,'./'.$fileName)){
//            $fileName = '';
//        }
//        imagedestroy($target_image);
//        return $fileName;
//    }
    public function getJson($url = '', $param = [] ,$contentType = 'json'){
        $ch = curl_init();
        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 请求参数类型
        $param = $contentType == 'json' ? urldecode(json_encode($param)) : http_build_query($param);
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // post提交
        if($param){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 执行并接收响应结果
        $output = curl_exec($ch);
        //   var_dump($output);
        // 关闭curl
        curl_close($ch);
        return $output ;

    }
}
